package com.example.controller;

import com.example.ProgramProcessor;
import org.springframework.web.bind.annotation.*;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liuzhiqiang
 */
@RestController
@RequestMapping("/loader")
@CrossOrigin
public class InitController {

    private static Map<String, ProgramProcessor> map = new ConcurrentHashMap<>();


    @GetMapping("/jar")
    public String loaderJar() {
        try {
            URL url = new URL("https://yun-cunchu.oss-cn-beijing.aliyuncs.com/spring-example-1.0-SNAPSHOT.jar");
            URLClassLoader classLoader = new URLClassLoader(new URL[]{url});
            Class cls = classLoader.loadClass("com.example.ProgramProcessorImpl");
            ProgramProcessor bean = (ProgramProcessor) cls.newInstance();
            String beanName = bean.getBeanName();
            map.put(beanName, bean);
        } catch (Exception e) {
            return "loader-error";
        }
        return "loader-success";
    }


    @PostMapping("/javaFile")
    public String loaderJavaFile(String javaCode) throws IOException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
        // 指定要编译的Java源文件


        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.out.println("Java compiler not available");
            return "Java compiler not available";
        }

        // 创建文件管理器，用于处理源文件和类文件
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        // 设置要编译的源文件
        File javaFile = new File("Test.java");
        FileWriter fileWriter = new FileWriter(javaFile);
        fileWriter.write(javaCode);
        fileWriter.close();
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFile);

        // 创建编译任务
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);

        // 执行编译任务
        boolean result = task.call();
        if (result) {

            URL classDirURL = new URL("file:/D:/private-projects/springboot/");
            URLClassLoader classLoader = new URLClassLoader(new URL[]{classDirURL});
            Class<?> myClass = classLoader.loadClass("Test");
            Method method = myClass.getMethod("test");
            method.setAccessible(true);
            method.invoke(myClass.newInstance());
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }

        // 关闭文件管理器
        try {
            fileManager.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Compilation is successful";
    }

    @PostMapping("/test/{name}")
    public Object test(@PathVariable("name") String name, @RequestBody Object obj) {
        Object o = map.get(name).programFunction(obj);
        return o;
    }

}
